//
//  EJCommentMenuView.m
//  EJiangOSbeta
//
//  Created by 刘爽 on 2019/10/10.
//  Copyright © 2019 Joyssom. All rights reserved.
//

#import "EJCommentMenuView.h"
#import <Masonry/Masonry.h>

@interface EJCommentMenuView () {
    CGFloat _maxWidth;
    CGFloat _minHornLeading;
    CGFloat _currentWidth;
    CGFloat _hornWidth;
}

@property (nonatomic, strong) UIView * bgView;

@property (nonatomic, strong) UIView * mainView;

@property (nonatomic, strong) UIImageView * hornView;

@property (nonatomic, assign) CGSize screenSize;

@end

@implementation EJCommentMenuView

- (instancetype)init {
    self = [super init];
    if (self) {
        _maxWidth = CGRectGetWidth([UIScreen mainScreen].bounds) - 28;
        _minHornLeading = 14;
        _hornWidth = 22;
        
        _screenSize = [UIScreen mainScreen].bounds.size;
                
        _mainView = [[UIView alloc] init];
        _mainView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.9];
        _mainView.layer.cornerRadius = 8;
        [self addSubview:_mainView];
        
        _hornView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"comment_menu_horn"]];
        [self addSubview:_hornView];
        
        [_mainView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(self);
            make.height.mas_equalTo(40);
            
        }];
        [_hornView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.mas_bottom).offset(0);
            make.top.equalTo(_mainView.mas_bottom).offset(0);
            make.size.mas_equalTo(CGSizeMake(_hornWidth, 10));
            make.left.equalTo(self.mas_left).offset(0);
        }];
        
        
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    // 更新UI
    if (self.superview == nil || self.isHidden == YES) {
        return;
    }
    
    CGSize currentSize = [UIScreen mainScreen].bounds.size;
    if (CGSizeEqualToSize(currentSize, _screenSize)) {
        return;
    }
    _screenSize = currentSize;
    _maxWidth = CGRectGetWidth([UIScreen mainScreen].bounds) - 28;
    [self hide];
}

- (void)setMenuTitles:(NSArray<NSString *> *)menuTitles {
    // 判断是否需要修改
    BOOL needReload = NO;
    if (_menuTitles.count != menuTitles.count) {
        needReload = YES;
    }
    for (NSString *str in menuTitles) {
        if (![_menuTitles containsObject:str]) {
            needReload = YES;
        }
    }
    if (needReload == NO) {
        return;
    }
    _menuTitles = menuTitles;
    for (UIView * objView in _mainView.subviews) {
        [objView removeFromSuperview];
    }
    __block CGFloat width = 0;
    [_menuTitles enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx > 0) {
            UIView * line = [[UIView alloc] init];
            line.backgroundColor = [UIColor colorWithWhite:1 alpha:0.8];
            line.frame = CGRectMake(width, 0, 1 / [UIScreen mainScreen].scale, 40);
            width += CGRectGetWidth(line.frame);
            [_mainView addSubview:line];
        }
        UILabel * label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = obj;
        label.tag = idx;
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:14];
        [label sizeToFit];
        label.frame = CGRectMake(width, 0, CGRectGetWidth(label.frame) + 42, 40);
        width += CGRectGetWidth(label.frame);
        [_mainView addSubview:label];
        
        
        label.userInteractionEnabled = YES;
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleClickLabel:)];
        [label addGestureRecognizer:tap];
        
    }];
    _currentWidth = width > _maxWidth ? _maxWidth : width;
    [_mainView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(_currentWidth);
    }];
}

- (void)showInPoint:(CGPoint)point {
    [self removeFromSuperview];
    _show = YES;
    UIWindow * window = [UIApplication sharedApplication].delegate.window;
    self.bgView.frame = window.bounds;
    
    self.hidden = NO;
    
    CGRect frame =  self.frame;
    frame.size = CGSizeMake(_currentWidth, 50);
    frame.origin.y = point.y - frame.size.height - 10;
    
    // 假定point.x为menuView的midX,矫正menuView的origin.x,确定menuView.frame
    frame.origin.x = point.x - CGRectGetWidth(frame) / 2;
    if (frame.origin.x < _minHornLeading) {
        frame.origin.x = _minHornLeading;
    } else if (CGRectGetMaxX(frame) > (CGRectGetWidth(window.bounds) - _minHornLeading)) {
        frame.origin.x = CGRectGetWidth(window.bounds) - _minHornLeading - CGRectGetWidth(frame);
    }
    
    UIEdgeInsets safeArea = UIEdgeInsetsZero;
    if (@available(iOS 11.0, *)) {
        safeArea = window.safeAreaInsets;
    }
    // 矫正menuView的y并且同步更新horn.top/bottom
    if (frame.origin.y < safeArea.top) {
        frame.origin.y = point.y + 10;
        _hornView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.0, -1.0);
        [_mainView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self).offset(10);
        }];
        [_hornView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.mas_bottom).offset(-40);
            make.top.equalTo(_mainView.mas_bottom).offset(-50);
        }];
    } else {
        _hornView.transform = CGAffineTransformIdentity;
        [_mainView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self);
        }];
        [_hornView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.mas_bottom).offset(0);
            make.top.equalTo(_mainView.mas_bottom).offset(0);
        }];
    }
    
    self.frame = frame;
    
    // 确定 horn的x
    CGFloat hornMidX = _hornWidth / 2;
    if (point.x >= CGRectGetMinX(frame)) {
        hornMidX = point.x - CGRectGetMinX(frame);
        if (hornMidX + _hornWidth > CGRectGetWidth(frame)) {
            hornMidX = CGRectGetWidth(frame) - _hornWidth;
        }
    }
    
    CGFloat hornX = hornMidX - _hornWidth / 2;
    if (hornX < _mainView.layer.cornerRadius) {
        hornX = _mainView.layer.cornerRadius;
    } else if (hornX + _hornWidth == CGRectGetWidth(frame)) {
        hornX = CGRectGetWidth(frame) - _hornWidth - _mainView.layer.cornerRadius;
    }
    
    [_hornView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left).offset(hornX);
    }];
    
    [window addSubview:_bgView];
    [window addSubview:self];
}

- (void)hide {
    _show = NO;
    if (self.superview) {
        [_bgView removeFromSuperview];
        [self removeFromSuperview];
    }
    self.hidden = YES;
}

#pragma mark - action
- (void)handleClickLabel:(UITapGestureRecognizer *)gesture {
    [self hide];
    if ([self.delegate respondsToSelector:@selector(ej_commentMenuViewDidClickAtIndex:)]) {
        [self.delegate ej_commentMenuViewDidClickAtIndex:gesture.view.tag];
    }
}

- (void)handleTapBgView {
    [self hide];
    if ([self.delegate respondsToSelector:@selector(ej_commentMenuViewDidHide)]) {
        [self.delegate ej_commentMenuViewDidHide];
    }
}

#pragma mark - getter or setter
- (UIView *)bgView {
    if (!_bgView) {
        _bgView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _bgView.backgroundColor = [UIColor clearColor];
        
        UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapBgView)];
        [_bgView addGestureRecognizer:tapGesture];
    }
    return _bgView;
}


@end
